﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using David.Framework.Core.Extensions;
using David.WebSite.Data;

namespace David.Framework.Web.Filter
{
    public class ExceptionHandlerAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            string controller = filterContext.RouteData.Values["controller"] as string;
            string action = filterContext.RouteData.Values["action"] as string;
            var url = filterContext.RequestContext.HttpContext.Request.Url;

            var prams = new Dictionary<string, string>();

            foreach (var p in filterContext.RequestContext.HttpContext.Request.Params.AllKeys)
            {
                if (p != null)
                {
                    prams.Add(p, filterContext.RequestContext.HttpContext.Request.Params[p]);
                }
            }
            LogDataService.Exception("{0}的{1}方法发生异常!".FormatWith(controller, action),
            filterContext.Exception.GetMessage(),
            url == null ? "" : url.AbsoluteUri,
            prams
            );

            filterContext.ExceptionHandled = true;

            filterContext.Result = new RedirectResult("/error");

        }
    }
}
